//
//  THRollcallViewController.m
//  Teacher-Help
//
//  Created by Taro on 15/10/23.
//  Copyright © 2015年 Taro. All rights reserved.
//

#import "THRollcallViewController.h"
#import "THStudentNameTableViewCell.h"
#import <AFNetworking/AFNetworking.h>
#import "THStudent.h"
#import <Masonry/Masonry.h>
#import "XYPieChart.h"
#import "NSDictionary+QuickCreat.h"

@interface THRollcallViewController ()<UITableViewDelegate,UITableViewDataSource,XYPieChartDataSource,XYPieChartDelegate>
@property (nonatomic , strong) UITableView * namelist;
@property (nonatomic , strong) UITableView * absenceList;
@property (nonatomic , strong) UITableView * detailList;
@property (nonatomic , strong) UISegmentedControl *segment;
@property (nonatomic , strong) NSMutableArray * resultarray;
@property (nonatomic , strong) NSMutableArray * model;
@property (nonatomic , strong) NSMutableArray * resubArray;
@property (nonatomic , strong) NSMutableArray * resubModel;


@property (nonatomic , strong) NSMutableSet * absenceArray;//缺席
@property (nonatomic , strong) NSMutableSet * leaveArray;//请假
@property (nonatomic , strong) NSMutableSet * laterArray;//迟到
@property (nonatomic , strong) NSMutableSet * resubmit;//补签

@property (nonatomic , strong) NSMutableArray * absenceModel;
@property (nonatomic , strong) NSMutableArray * leaveModel;
@property (nonatomic , strong) NSMutableArray * laterModel;
@property (nonatomic , strong) NSMutableArray * arriveModel;
@property (nonatomic , strong) NSMutableArray * detailShowModel;
@property (nonatomic , strong) NSMutableArray * detailTotalModel;
@property (nonatomic , strong) NSMutableSet * deletTagSet;



@property (nonatomic , strong) NSMutableSet * arriveArray; //已到
@property (nonatomic , strong) NSMutableSet * reLeaveArray;//请假
@property (nonatomic , strong) NSMutableSet * reLaterArray;//迟到


@property (nonatomic , strong) UIView * firstView;
@property (nonatomic , strong) UIView * secondView;
@property (nonatomic , strong) UIView * thirdView;
@property (nonatomic , strong) UIButton *submitBtn;

@property (nonatomic , assign) NSInteger submitTag;

//详情表 绘图。
@property (nonatomic , strong) XYPieChart * pieChart;
@property (strong, nonatomic) NSMutableArray *slices;
@property (strong, nonatomic) NSMutableArray *colorsOfSlice;
@property (nonatomic , strong) NSMutableArray * nameOfSlice;


@property (nonatomic , assign) CGFloat percentOfAbcense;
@property (nonatomic , assign) CGFloat percentOfLater;
@property (nonatomic , assign) CGFloat percentOfLeave;
@property (nonatomic , assign) CGFloat percentOfArrive;
@property (nonatomic , assign) NSInteger lastRow;
@property (nonatomic , assign) NSInteger lastLeaveRow;
@property (nonatomic , assign) NSInteger lastLaterRow;



@end

@implementation THRollcallViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBarController.tabBar.hidden = YES;
    _absenceArray = [[NSMutableSet alloc] init];
    _reLaterArray = [[NSMutableSet alloc] init];
    _reLeaveArray = [[NSMutableSet alloc] init];
    _leaveArray = [[NSMutableSet alloc] init];
    _laterArray = [[NSMutableSet alloc] init];
    _arriveArray = [[NSMutableSet alloc] init];
    
    
    //详情界面数据
    _absenceModel = [[NSMutableArray alloc] init];
    _arriveModel = [[NSMutableArray alloc] init];
    _leaveModel = [[NSMutableArray alloc] init];
    _laterModel = [[NSMutableArray alloc] init];
    _deletTagSet = [[NSMutableSet alloc] init];
    _detailTotalModel = [NSMutableArray arrayWithObjects:_absenceModel,_laterModel,_leaveModel, nil];
//    _detailTotalModel = @[_absenceModel,_laterModel,_leaveModel,_arriveModel];
    _detailShowModel = [[NSMutableArray alloc] init];
    
    
    //设置补签页面
    NSArray *segmentData = @[@"点名",@"详情",@"补签"];
    _segment = [[UISegmentedControl alloc] initWithItems:segmentData];
    [_segment setTintColor:[UIColor whiteColor]];
    [_segment setBackgroundColor:XColor(64, 185, 216, 1)];
//    segment.backgroundColor = [UIColor whiteColor];
    self.navigationItem.titleView = _segment;
    self.navigationItem.titleView.frame = CGRectMake(0, 0, 150, 30);
    _segment.selectedSegmentIndex = 0;
    [_segment addTarget:self action:@selector(didselectsegment:) forControlEvents:UIControlEventValueChanged];
    self.thirdView = [[UIView alloc] init];
    self.thirdView.backgroundColor = [UIColor greenColor];
    self.thirdView.frame = self.view.frame;
    [self.view addSubview:self.thirdView];
    self.secondView = [[UIView alloc] init];
    self.secondView.backgroundColor = [UIColor whiteColor];
    self.secondView.frame = self.view.frame;
    [self.view addSubview:self.secondView];
    self.firstView = [[UIView alloc] init];
    self.firstView.backgroundColor = [UIColor yellowColor];
    self.firstView.frame = self.view.frame;
    [self.view addSubview:self.firstView];
    
    
//
   
    self.namelist = [[UITableView alloc] init];
    self.namelist.dataSource = self;
    self.namelist.delegate = self;
    self.namelist.frame = CGRectMake(0,0, screenW, screenH);
     self.namelist.contentInset=UIEdgeInsetsMake(84, 0, 0, 0);
    
    [self.firstView addSubview:self.namelist];
    UILabel *number = [[UILabel alloc] init];
    number.frame = CGRectMake(0, 64, screenW/3, 20);
    number.text = @"学号";
    [number setTextAlignment:NSTextAlignmentCenter];
    number.backgroundColor = [UIColor whiteColor];
    [self.firstView addSubview:number];
    UILabel * name = [[UILabel alloc] init];
    name.frame = CGRectMake(screenW/3,64, screenW/3, 20);
    name.text = @"姓名";
    name.backgroundColor = [UIColor whiteColor];
    [name setTextAlignment:NSTextAlignmentCenter];
    [self.firstView addSubview:name];
    UILabel *absence = [[UILabel alloc] init];
    absence.frame = CGRectMake(screenW*2/3, 64, screenW/3, 20);
    absence.text = @"缺勤 ";
    [absence setTextAlignment:NSTextAlignmentCenter];
    absence.backgroundColor = [UIColor whiteColor];
    [self.firstView addSubview:absence];
    
    
  


    
    
    _submitBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _submitBtn.frame = CGRectMake(0, 0, 60, 40);
    _submitBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_submitBtn setTitle:@"提交点名" forState:UIControlStateNormal];
    [_submitBtn setTintColor:[UIColor whiteColor]];
    _submitTag = 0;//默认提交点名
    [_submitBtn addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *sub = [[UIBarButtonItem alloc] initWithCustomView:_submitBtn];
    self.navigationItem.rightBarButtonItem = sub;
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"    返回" style:UIBarButtonItemStylePlain target:self action:@selector(backToIndex)];
    
    _arriveModel = [NSMutableArray arrayWithObjects:@12,@12, nil];
    [self getStudentTable:^(NSMutableArray *array) {
        NSMutableArray *modelarray = [NSMutableArray array];
        for (NSDictionary *dict in array) {
            THStudent *student = [THStudent studentWithDic:dict];
            [modelarray addObject:student];
        }
        _model = modelarray;
        _arriveModel = [modelarray mutableCopy];
        [_detailTotalModel addObject:_arriveModel];
        //判断是否重复点击cell
        _lastRow = modelarray.count + 1;
        _lastLeaveRow = _lastRow;
        _lastLaterRow = _lastRow;
//        THLog(@"ar%@",_arriveModel);
//        THLog(@"to%@",_detailTotalModel);

   
        [self.namelist reloadData];
    }];
    
    /*
     *
     *补签view
     *
     */
    
    self.absenceList = [[UITableView alloc] init];
    self.absenceList.dataSource = self;
    self.absenceList.delegate = self;
    self.absenceList.frame = CGRectMake(0,20, screenW, screenH);
    [self.thirdView addSubview:self.absenceList];
    
  
    UILabel *number1 = [[UILabel alloc] init];
    number1.frame = CGRectMake(50, 64, screenW/3-50, 20);
    number1.text = @"学号";
    number1.backgroundColor = [UIColor whiteColor];
    [self.thirdView addSubview:number1];
    UILabel * name1 = [[UILabel alloc] init];
    name1.frame = CGRectMake(screenW/3, 64, screenW/3, 20);
    name1.text = @"姓名";
    name1.backgroundColor = [UIColor whiteColor];
    [name1 setTextAlignment:NSTextAlignmentCenter];
    [self.thirdView addSubview:name1];
//    UILabel *absence1 = [[UILabel alloc] init];
//    absence1.frame = CGRectMake(screenW*2/3, 0, screenW/3, 20);
//    absence1.text = @"缺勤 ";
//    [absence1 setTextAlignment:NSTextAlignmentCenter];
//    [self.thirdView addSubview:absence1];
    
    

 
    
    
    
    
    /*
     *详情view
     *
     */
   

    
    
}




- (void)setChartView{
    self.pieChart = [[XYPieChart alloc] init];
    self.pieChart.delegate = self;
    self.pieChart.dataSource = self;
    [self.pieChart setStartPieAngle:M_PI];
    [self.pieChart setAnimationSpeed:1.0];
    [self.pieChart setPieRadius:screenH/5];//饼图半径
    [self.pieChart setLabelFont:[UIFont fontWithName:@"DBLCDTempBlack" size:20]];
    [self.pieChart setLabelRadius:screenH/6-20];//数据标签出现的位置
    [self.pieChart setPieBackgroundColor:[UIColor colorWithWhite:0.95 alpha:1]];
    [self.pieChart setPieCenter:CGPointMake(screenW/2, 84+screenH/5)];
    [self.pieChart setLabelShadowColor:[UIColor blackColor]];
//    [self.pieChart setShowPercentage:NO];
    NSNumber *one = [NSNumber numberWithFloat:_percentOfAbcense*360];
    NSNumber *two = [NSNumber numberWithFloat:_percentOfLeave*360];
    NSNumber *three = [NSNumber numberWithFloat:_percentOfLater*360];
    NSNumber *four = [NSNumber numberWithFloat:_percentOfArrive*360];
    _slices = [NSMutableArray arrayWithObjects:one,two,three,four, nil];
    _nameOfSlice = [NSMutableArray arrayWithObjects:@"缺席",@"请假",@"迟到",@"已到",nil];
    
    self.colorsOfSlice =[NSMutableArray arrayWithObjects:
                         [UIColor colorWithRed:246/255.0 green:155/255.0 blue:0/255.0 alpha:1],
                         [UIColor colorWithRed:129/255.0 green:195/255.0 blue:29/255.0 alpha:1],
                         [UIColor colorWithRed:62/255.0 green:173/255.0 blue:219/255.0 alpha:1],
                         [UIColor colorWithRed:229/255.0 green:66/255.0 blue:115/255.0 alpha:1],
                       nil];
    [self.pieChart reloadData];
    [self.secondView addSubview:self.pieChart];
    
    
    NSArray *array = [_deletTagSet allObjects];
    
    NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj2 compare:obj1];
    }];
    for (int i = 0; i < sortArray.count; i++) {
        [_arriveModel removeObjectAtIndex:[[sortArray objectAtIndex:i] integerValue]];
        
    }
 
    
    
    NSString *s1 = @"frame";
    NSString *s2 = @"text";
    NSString *s3 = @"backgroundColor";
    NSString *s4 = @"tag";
    NSArray *keys = @[s1,s2,s3,s4];
    
    NSArray *models = @[
                        NSDictionary.setValuesAndKeys(@[[NSValue valueWithCGRect:CGRectMake(0,screenH/2+50 , screenW/4, 30)],[NSString stringWithFormat:@"缺席 : %ld",_absenceArray.count],[UIColor colorWithRed:246/255.0 green:155/255.0 blue:0/255.0 alpha:1],@0 ],keys),
                        NSDictionary.setValuesAndKeys(@[[NSValue valueWithCGRect:CGRectMake(screenW/4, screenH/2+50, screenW/4, 30)],[NSString stringWithFormat:@"迟到 : %ld",_laterArray.count],[UIColor colorWithRed:62/255.0 green:173/255.0 blue:219/255.0 alpha:1],@1 ],keys),
                        NSDictionary.setValuesAndKeys(@[[NSValue valueWithCGRect:CGRectMake(screenW/4*2, screenH/2+50, screenW/4, 30)],[NSString stringWithFormat:@"请假 : %ld",_leaveArray.count],[UIColor colorWithRed:129/255.0 green:195/255.0 blue:29/255.0 alpha:1],@2 ],keys),
                        NSDictionary.setValuesAndKeys(@[[NSValue valueWithCGRect:CGRectMake(screenW/4*3, screenH/2+50, screenW/4, 30)],[NSString stringWithFormat:@"已到 : %ld",_arriveModel.count],[UIColor colorWithRed:229/255.0 green:66/255.0 blue:115/255.0 alpha:1],@3 ],keys),
                        ];
    
    
    for (NSDictionary *dict in models) {
        UIButton *button = [[UIButton alloc] init];
        [self.secondView addSubview:button];
        [button setTitle:dict[@"text"] forState:UIControlStateNormal];
         button.backgroundColor = dict[@"backgroundColor"];
        [button setValue:dict[@"frame"] forKey:@"frame"];
        [button setValue:dict[@"tag"] forKey:@"tag"];
        [button addTarget:self action:@selector(changeAbsenceTable:) forControlEvents:UIControlEventTouchUpInside];
        
//        [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
//            [label setValue:obj forKeyPath:key];
//        }];
        
    }
    
    
    self.detailList = [[UITableView alloc] init];
    self.detailList.frame = CGRectMake(0, screenH/2+50+30, screenW, screenH-(screenH/2+50+30));
    self.detailList.dataSource = self;
    self.detailList.delegate = self;
    [self.secondView addSubview:self.detailList];

    
}
- (void)changeAbsenceTable:(id)sender{
//    _test3 = [_test4 objectAtIndex:[sender tag]];

    _detailShowModel = [_detailTotalModel objectAtIndex:[sender tag]];
    [self.detailList reloadData];
    
//    THLog(@"%ld",_detailShowModel.count);
   
    
}





- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    if (tableView == self.namelist) {
            return _model.count;
    }else if(tableView == self.absenceList){
        return _resubModel.count;
    }else{
        return _detailShowModel.count;
    }

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    tableView = self.namelist;
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (tableView == self.namelist) {
        
        
            THStudent *student = _model[indexPath.row];
            [_deletTagSet addObject:[NSNumber numberWithLong:indexPath.row]];
            cell.backgroundColor = [UIColor redColor];
            [_absenceArray addObject:student.studentId];
            [_leaveArray removeObject:student.studentId];
            [_laterArray removeObject:student.studentId];
        if (_lastRow != indexPath.row) {
            THStudent *detail = [[THStudent alloc] init];
            detail.name = student.name;
            detail.studentNo = student.studentNo;
            [_absenceModel addObject:detail];
            _lastRow = indexPath.row;
        }
//        [_absenceModel addObject:detail];
//        _lastRow = indexPath.row;
        THLog(@"%ld",_absenceModel.count);
        
        
//        float abcenseCount = _absenceArray.count;
//        float total = _model.count;
       
    }else if(tableView == self.absenceList){
//        THStudent *student = _resubModel[indexPath.row];
//        [self.resubmit addObject:student.studentId];
//        cell.backgroundColor = [UIColor redColor];
        
    }
   
  

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
    });
}





- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    NSString *ID = [NSString stringWithFormat:@"cell%ld",indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
        if (tableView == self.detailList) {
           
           
        }else{
        UILabel *number = [[UILabel alloc] init];
        number.frame = CGRectMake(50, 0, screenW/3, cell.frame.size.height);
        
        [cell addSubview:number];
        UILabel *name = [[UILabel alloc] init];
        name.frame = CGRectMake(screenW/3, 0, screenW/3, cell.frame.size.height);
        name.adjustsFontSizeToFitWidth = YES;
        
        [name setTextAlignment:NSTextAlignmentCenter];
        [cell addSubview:name];
        UILabel *laterTime = [[UILabel alloc] init];
        laterTime.frame = CGRectMake(screenW*2/3, 0, screenW/3, cell.frame.size.height);
        [laterTime setTextAlignment:NSTextAlignmentCenter];
        
        [cell addSubview:laterTime];
        
        UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, cell.frame.size.height)];
        if (tableView == self.namelist) {
            THStudent *student = _model[indexPath.row];
            number.text = [NSString stringWithFormat:@"%@",student.studentNo];
            laterTime.text = [NSString stringWithFormat:@"%@次",student.lateTimes];
            name.text = student.name;
            if ([student.lateTimes intValue] == 0) {
                laterTime.textColor = XColor(89, 200, 139, 1);;
                icon.image = [UIImage imageNamed:@"green"];
            }else if([student.lateTimes intValue] > 0 && [student.lateTimes intValue] < 3){
                icon.image = [UIImage imageNamed:@"orange"];
                laterTime.textColor = XColor(253, 175, 105, 1);
            }else{
                icon.image = [UIImage imageNamed:@"red"];
                laterTime.textColor = XColor(251, 52, 46, 1);
            }
            
        }else if (tableView == self.absenceList){
            THStudent *student = _resubModel[indexPath.row];
            number.text = [NSString stringWithFormat:@"%@",student.studentNo];
            name.text = student.name;
            icon.image = [UIImage imageNamed:@"red"];
        }
        
        [cell addSubview:icon];

       
        }}
    if (tableView == self.detailList) {

        THStudent *student = _detailShowModel[indexPath.row];
        cell.textLabel.text = student.name;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",student.studentNo];

    }
    

    
    
    return cell;
}

//侧滑显示另外两个按钮
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
}


- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (tableView == self.namelist) {
        UITableViewRowAction *leave = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"请假" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            
      
                THStudent *student = _model[indexPath.row];
                UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                cell.backgroundColor = XColor(64, 185, 216, 1);
                
                [_absenceArray removeObject:student.studentId];
                [_leaveArray addObject:student.studentId];
                [_laterArray removeObject:student.studentId];
            if (_lastLeaveRow != indexPath.row) {
                THStudent *detail = [[THStudent alloc] init];
                detail.name = student.name;
                detail.studentNo = student.studentNo;
                [_leaveModel addObject:detail];
                [_deletTagSet addObject:[NSNumber numberWithLong:indexPath.row]];
                _lastLeaveRow = indexPath.row;
                THLog(@"请假名单%@",_leaveModel);
            }
            
           
            [tableView setEditing:NO];
            
        }];
        leave.backgroundEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        
        UITableViewRowAction *later = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"迟到" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
           
                THStudent *student = _model[indexPath.row];
                UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                
                cell.backgroundColor = [UIColor greenColor];
                [_absenceArray removeObject:student.studentId];
                [_laterArray addObject:student.studentId];
                [_leaveArray removeObject:student.studentId];
            
            if (_lastLaterRow != indexPath.row) {
                THStudent *detail = [[THStudent alloc] init];
                detail.name = student.name;
                detail.studentNo = student.studentNo;
                [_laterModel addObject:detail];
                [_deletTagSet addObject:[NSNumber numberWithLong:indexPath.row]];
                _lastLaterRow = indexPath.row;
            }
            
            
           
             [tableView setEditing:NO];
        }];
        
        
        UITableViewRowAction *cancel = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"撤销"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
            
            
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath ];
            cell.backgroundColor = [UIColor whiteColor];
            THStudent *student = _model[indexPath.row];
            [_absenceArray removeObject:student.studentId];
            [_leaveArray removeObject:student.studentId];
            [_laterArray removeObject:student.studentId];
            
            [_deletTagSet removeObject:[NSNumber numberWithLong:indexPath.row]];
            THLog(@"缺席名单%@",_absenceArray);
            THLog(@"缺席%@",_leaveArray);
             [tableView setEditing:NO];
            //        [tableView reloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationMiddle];
        }];
        later.backgroundColor = [UIColor redColor];

       
        
        return @[cancel,later,leave];
    }else if(tableView == self.absenceList){
        
        UITableViewRowAction *arrive = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"已到" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            THStudent *student = _resubModel[indexPath.row];
            [_arriveArray addObject:student.studentId];
            [_reLaterArray removeObject:student.studentId];
            [_reLeaveArray removeObject:student.studentId];
            THLog(@"%@",_arriveArray);
             [tableView setEditing:NO];
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.backgroundColor = [UIColor orangeColor];
            
        }];
        arrive.backgroundColor = [UIColor orangeColor];
        
        UITableViewRowAction *leave = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"请假" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            THStudent *student = _resubModel[indexPath.row];
            [_reLeaveArray addObject:student.studentId];
            [_arriveArray removeObject:student.studentId];
            [_reLaterArray removeObject:student.studentId];
            THLog(@"补请假%@",_reLeaveArray);
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.backgroundColor = XColor(64, 185, 216, 1);
             [tableView setEditing:NO];
         
        }];
        leave.backgroundEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        
        UITableViewRowAction *later = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"迟到" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            THStudent *student = _resubModel[indexPath.row];
            [_reLaterArray addObject:student.studentId];
            [_arriveArray removeObject:student.studentId];
            [_reLeaveArray removeObject:student.studentId];
            THLog(@"补迟到%@",_reLaterArray);
             [tableView setEditing:NO];
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.backgroundColor = [UIColor greenColor];
            
        }];
        later.backgroundColor = [UIColor greenColor];
        
        UITableViewRowAction *cancel = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"撤销"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
            
            
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath ];
            cell.backgroundColor = [UIColor whiteColor];
            THStudent *student = _resubModel[indexPath.row];
            [_arriveArray removeObject:student.studentId];
            [_reLaterArray removeObject:student.studentId];
            [_reLeaveArray removeObject:student.studentId];
             [tableView setEditing:NO];
            //        [tableView reloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationMiddle];
        }];
        later.backgroundColor = [UIColor redColor];
        
        return @[cancel,later,leave,arrive];

    }
    
    return nil;
  
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
}


//点名数据请求
- (void)getStudentTable:(void(^)( NSMutableArray  * array))success{
    
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
    NSString *url = [NSString stringWithFormat:@"http://120.26.83.51/demo/test_create_test/?courseId=%@",_courseId];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {

        NSMutableArray *array = responseObject[@"class"];
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            if (success) {
                success(array);
            }
        }];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        THLog(@"%@",error);
    }];
    
    
}

//缺勤数据请求
- (void)getAbsenceListData:(void(^)(NSMutableArray  * array))success{
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
    NSDictionary *requestData = @{
                                  @"courseId" : _courseId,
                                  @"weekOrdinal" : _weekOrdinal
                                  };
    [manager POST:@"http://120.26.83.51/demo/special_offer/" parameters:requestData success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        NSMutableArray *array = responseObject[@"class"];
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            if (success) {
                success(array);
            }
        }];
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        THLog(@"%@",error);
    }];
}



//返回按钮
//- (void)backToIndex{
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"点名单还没提交，确定要退出吗？" preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [self.navigationController popViewControllerAnimated:YES];
//    }];
//    [alert addAction:cancel];
//    [alert addAction:confirm];
//    [self presentViewController:alert animated:YES completion:nil];
//    
//}
//提交按钮
- (void)submit{
    
    
    if (_submitTag == 0) {
        AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.requestSerializer=[AFJSONRequestSerializer serializer];
        //数据结构类型
        NSArray *absence = [_absenceArray allObjects];
        NSArray *leave = [_leaveArray allObjects];
        
        
        //    THLog(@"%@",array);
        
        
        NSDictionary *dict = @{
                               @"studentIdForAbsence" : absence,
                               @"courseId" : _courseId,
                               @"studentIdForLeave" :leave
                        
                               };
        [manager POST:@"http://120.26.83.51/demo/absence_record/" parameters:dict success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            THLog(@"%@",responseObject[@"status"]);
            NSNumber *status = responseObject[@"status"];
            if ([status integerValue] == 1) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"提交成功！" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                    [self.navigationController popViewControllerAnimated:YES];
                }];
                [alert addAction:confirm];
                [self presentViewController:alert animated:YES completion:nil];
                float total = _model.count;
                float abcenseCount = _absenceArray.count;
                float leaveCount = _leaveArray.count;
                float laterCount = _laterArray.count;
                float arriveCount = total - abcenseCount - leaveCount - laterCount;
                _percentOfAbcense = abcenseCount/total ;
                _percentOfArrive = arriveCount/total ;
                _percentOfLater = laterCount/total ;
                _percentOfLeave = leaveCount/total ;
              
                [self.pieChart reloadData];
                [self setChartView];
                self.firstView.hidden = YES;
                self.secondView.hidden = NO;
                self.segment.selectedSegmentIndex = 1;
                
                
                _detailShowModel = _absenceModel;
                [self.detailList reloadData];
                
                
                UIView *view = [[UIView alloc] initWithFrame:self.firstView.frame];
                view.backgroundColor = XColor(0, 0, 0, 0.6);
    
                [self.firstView addSubview:view];
                
                
            }else{
                UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"提交失败" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
                [alertView show];
                
            }
            
        } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
            THLog(@"%@",error);
            UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"请确定网络是否连接" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alertView show];
            
        }];
      
        
    }else if(_submitTag == 1){
        AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.requestSerializer=[AFJSONRequestSerializer serializer];
        //数据结构类型
        NSArray *later = [_reLaterArray allObjects];
        NSArray *leave = [_reLeaveArray allObjects];
        NSArray *arrive = [_arriveArray allObjects];
        
  
        
        
        NSDictionary *dict = @{
                               @"courseId" : _courseId,
                               @"weekOrdinal" : _weekOrdinal,
                               @"studentIdForMiss" :arrive,
                               @"studentIdForLeave" :leave,
                               @"studentIdForLate" :later
                               };
        [manager POST:@"http://120.26.83.51/demo/record_again/" parameters:dict success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            THLog(@"%@",responseObject[@"status"]);
            NSNumber *status = responseObject[@"status"];
            if ([status integerValue] == 1) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"提交成功！" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self.navigationController popViewControllerAnimated:YES];
                }];
                [alert addAction:confirm];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"提交失败" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
                [alertView show];
                
            }
            
        } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
            THLog(@"%@",error);
            UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"请确定网络是否连接" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alertView show];
            
        }];

    }
    
}

//segment切换view
- (void)didselectsegment:(UISegmentedControl *)sege{
    if (sege.selectedSegmentIndex == 0) {
        [_submitBtn setTitle:@"提交点名" forState:UIControlStateNormal];
        _submitTag = 0;
        self.firstView.hidden = NO;
        self.secondView.hidden = YES;
        self.thirdView.hidden = YES;
    }else if (sege.selectedSegmentIndex == 1){
        [self.pieChart reloadData];
        self.firstView.hidden = YES;
        self.secondView.hidden = NO;
        self.thirdView.hidden = YES;
        
    }else if (sege.selectedSegmentIndex == 2){
        [_submitBtn setTitle:@"提交补签" forState:UIControlStateNormal];
        _submitTag = 1;
        self.firstView.hidden = YES;
        self.secondView.hidden = YES;
        self.thirdView.hidden = NO;
        [self getAbsenceListData:^(NSMutableArray *array) {
            NSMutableArray *modelarray = [NSMutableArray array];
            for (NSDictionary *dict in array) {
                THStudent *student = [THStudent studentWithDic:dict];
                [modelarray addObject:student];
            }
            _resubModel = modelarray;
            
            [self.absenceList reloadData];
        }];
    }
}

//隐藏tabbar
- (void)viewWillDisappear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
    
}


//绘图
- (NSUInteger)numberOfSlicesInPieChart:(XYPieChart *)pieChart
{
    
    return self.slices.count;
}

- (CGFloat)pieChart:(XYPieChart *)pieChart valueForSliceAtIndex:(NSUInteger)index
{
    return [[self.slices objectAtIndex:index] integerValue];
}

- (UIColor *)pieChart:(XYPieChart *)pieChart colorForSliceAtIndex:(NSUInteger)index
{
    return [self.colorsOfSlice objectAtIndex:(index % self.colorsOfSlice.count)];
}

- (NSString *)pieChart:(XYPieChart *)pieChart textForSliceAtIndex:(NSUInteger)index{
    return [self.nameOfSlice objectAtIndex:index];
}


@end
